<template>
  <div class="login-container">
    <!-- 左边 -->
    <div class="logo" />
    <!-- 右边 -->
    <div class="form">
      <h1>智慧园区登录</h1>
      <el-card shadow="never" class="login-card">
        <!--登录表单-->
        <el-form ref="loginRef" :model="loginForm" :rules="loginRules" label-position="top">
          <el-form-item prop="username" label="账号">
            <el-input v-model="loginForm.username" placeholder="请输入账号" />
          </el-form-item>
          <el-form-item prop="password" label="密码">
            <el-input v-model="loginForm.password" show-password placeholder="请输入密码" />
          </el-form-item>
          <el-form-item prop="isAgree">
            <el-checkbox v-model="rememberMe">记住我</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button style="width:350px" type="primary" @click="onLogin">登录</el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </div>
  </div>
</template>

<script>
export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      },
      loginRules: {
        username: [
          { required: true, message: '请输入账号', trigger: 'blur' },
          { pattern: /^\w{4,10}$/, message: '账号格式不正确', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 16, message: '密码长度应该为6-16位之间', trigger: 'blur' }
        ]
      },
      rememberMe: false
    }
  },
  created() {
    // 页面创建时，从本地存储中恢复用户信息
    const storedUser = JSON.parse(localStorage.getItem('userInfo'))
    if (storedUser) {
      this.loginForm.username = storedUser.username
      this.loginForm.password = storedUser.password
      this.rememberMe = true
    }
  },
  methods: {
    async onLogin() {
      await this.$refs.loginRef.validate() // 校验表单
      await this.$store.dispatch('user/login', this.loginForm) // 登录
      if (this.rememberMe) {
        // 存储用户信息
        localStorage.setItem('userInfo', JSON.stringify(this.loginForm))
      } else {
        // 清除用户信息
        localStorage.removeItem('userInfo')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.login-container{
  display: flex;
  align-items: stretch;
  height: 100vh;
 .logo {
    flex: 3;
    background: rgba(38, 72, 176) url(../../assets/common/login_back.png) no-repeat center / cover;
    border-top-right-radius: 60px;
  }
 .form {
    flex: 2;
    display: flex;
    flex-direction: column;
    justify-content: center;
    padding-left: 176px;

   .el-card {
      border: none;
      padding: 0;
    }

    h1 {
      padding-left: 20px;
      font-size: 24px;
    }

   ::v-deep.el-input {
      width: 350px;
      height: 44px;
     .el-input__inner {
        background: #f4f5fb;
      }
    }

    ::v-deep.el-checkbox {
      color: #606266;
    }
  }
}
</style>
